import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;

public class MyAvgUDAF extends UDAF {

    public static class MyAvgUDAFEvaluator implements UDAFEvaluator {
        private Accumulator accumulator;

        public MyAvgUDAFEvaluator() {
            init();
        }

        public void init() {
            accumulator = new Accumulator();
        }

        // 每来一条数据，该如何聚合
        public boolean iterate(Integer value) {

            accumulator.count++;

            accumulator.sum += value;

            return true;
        }


        // 局部聚合的结果如何获取
        public Accumulator terminatePartial() {

            return accumulator;
        }

        // 多个局部聚合结果如何合成全局聚合结果
        public boolean merge(Accumulator other) {

            accumulator.count += other.count;
            accumulator.sum += other.sum;

            return true;
        }

        // 最终全局结果如何取
        public Double terminate() {

            return (double) accumulator.sum / accumulator.count;
        }
    }


    public static class Accumulator {
        int count;
        int sum;
        public Accumulator(){
            count = 0;
            sum = 0;
        }


    }

}
